using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Duckov.Quests.UI;
using Duckov.Quests;
using Duckov.UI;
using Saves;

namespace TaskTracker
{
    public class ModBehaviour : Duckov.Modding.ModBehaviour
    {
        private GameObject? trackButton;
        private QuestViewDetails? currentQuestDetails;
        private Quest? lastTrackedQuest;
        
        // 追踪栈，最多5个任务
        private List<int> trackedQuestIds = new List<int>();
        private const int MAX_TRACKED_QUESTS = 5;
        
        // 五角星标识管理
        private Dictionary<int, GameObject> questStarIndicators = new Dictionary<int, GameObject>();
        
        // 任务进度跟踪
        private Dictionary<int, (int completed, int total)> questProgressCache = new Dictionary<int, (int, int)>();
        
        // 任务状态变化监听跟踪
        private Dictionary<int, List<Task>> listenedTasks = new Dictionary<int, List<Task>>();
        
        // 新UI面板相关
        private GameObject? mainPanel;
        private GameObject? toggleButton;
        private RectTransform? panelRect;
        private RectTransform? toggleButtonRect;
        private bool isPanelVisible = false; // 默认收起状态
        private bool isAnimating = false;
        
        // 面板位置状态
        private bool isPanelOnLeft = false; // true=左侧，false=右侧，初始为右侧
        
        // 双击检测相关
        private float lastUKeyPressTime = 0f;
        private const float DOUBLE_CLICK_TIME = 0.14f; // 双击时间间隔阈值（秒）
        private bool isWaitingForDoubleClick = false;
        private Coroutine? singleClickCoroutine = null;
        
        // 面板配置
        private const float PANEL_WIDTH = 360f;
        private const float ANIMATION_DURATION = 0.3f;
        private const float TOGGLE_BUTTON_WIDTH = 40f; // 增加按钮宽度以容纳"任务U"文本
        private const float TOGGLE_BUTTON_HEIGHT = 90f;
        
        // 存档相关
        private const string SAVE_KEY_PREFIX = "TaskTracker_Slot_";
        private bool isGameInitialized = false;
        private bool shouldHideOnStartup = true;
        private const float TOGGLE_BUTTON_SIZE = 40f;
        
        // 动态面板高度计算
        private float GetPanelHeight()
        {
            int trackedCount = trackedQuestIds.Count;
            if (trackedCount <= 3)
                return 800f;
            else if (trackedCount == 4)
                return 1025f;
            else
                return 1250f; // 5个或更多任务
        }
        
        // 更新面板高度
        private void UpdatePanelHeight()
        {
            if (panelRect != null)
            {
                float newHeight = GetPanelHeight();
                panelRect.sizeDelta = new Vector2(PANEL_WIDTH, newHeight);
                
                // 更新面板位置以保持正确的锚点
                UpdatePanelPositions(isPanelVisible);
            }
        }
        
        void Awake()
        {
            // 注册存档系统事件
            SavesSystem.OnSetFile += LoadData;
            LevelManager.OnLevelInitialized += OnLevelInitialized;
            
            // 注册主菜单事件
            MainMenu.OnMainMenuAwake += OnMainMenuAwake;
            
            // 启动时设置完全隐藏
            shouldHideOnStartup = true;
            isGameInitialized = false;
        }

        void Start()
        {
            // 监听任务完成事件
            RegisterQuestEvents();
            // 创建新的UI面板
            CreateMainPanel();
        }

        void Update()
        {
            // 定期检查任务详情变化
            CheckQuestDetailsChange();
            // 定期更新五角星标识
            UpdateQuestStarIndicators();
            // 检查任务进度变化
            CheckQuestProgressChanges();
            // 检查U键输入
            CheckToggleInput();
            // 检查L键输入（切换面板位置）
            CheckPanelPositionToggleInput();
        }

        void OnDestroy()
        {
            // 取消注册存档系统事件
            SavesSystem.OnSetFile -= LoadData;
            LevelManager.OnLevelInitialized -= OnLevelInitialized;
            
            // 取消注册主菜单事件
            MainMenu.OnMainMenuAwake -= OnMainMenuAwake;
            
            CleanupTrackButton();
            CleanupAllStarIndicators();
            CleanupMainPanel();
            CleanupTaskListeners();
            UnregisterQuestEvents();
        }

        protected override void OnAfterSetup()
        {
            base.OnAfterSetup();
        }

        protected override void OnBeforeDeactivate()
        {
            base.OnBeforeDeactivate();
            CleanupTrackButton();
            CleanupAllStarIndicators();
            CleanupMainPanel();
            UnregisterQuestEvents();
        }

        #region 新UI面板功能

        private void CreateMainPanel()
        {
            try
            {
                // 查找Canvas
                var canvas = FindObjectOfType<Canvas>();
                if (canvas == null)
                {
                    return;
                }

                // 创建主面板容器
                mainPanel = new GameObject("TaskTrackerMainPanel");
                mainPanel.transform.SetParent(canvas.transform, false);

                // 设置面板RectTransform
                panelRect = mainPanel.AddComponent<RectTransform>();
                panelRect.sizeDelta = new Vector2(PANEL_WIDTH, GetPanelHeight());
                
                // 添加半透明黑色背景
                var panelImage = mainPanel.AddComponent<Image>();
                panelImage.color = new Color(0, 0, 0, 0.7f); // 半透明黑色
                panelImage.type = Image.Type.Sliced;

                // 添加面板内容
                CreatePanelContent();

                // 创建独立的切换按钮（小耳朵）- 不作为面板的子对象
                CreateToggleButton(canvas);

                // 在所有UI元素创建完成后，统一设置位置和锚点
                UpdatePanelAnchorsAndPivot();
                UpdatePanelPositions(false); // 默认收起状态

                // 确保面板在最上层，但按钮在更上层
                mainPanel.transform.SetAsLastSibling();
                if (toggleButton != null)
                {
                    toggleButton.transform.SetAsLastSibling();
                }

                // 启动时完全隐藏面板和按钮
                if (shouldHideOnStartup)
                {
                    mainPanel.SetActive(false);
                    if (toggleButton != null)
                    {
                        toggleButton.SetActive(false);
                    }
                }

            }
            catch
            {
            }
        }

        private void CheckQuestProgressChanges()
        {
            var trackedQuests = GetTrackedQuests();
            bool progressChanged = false;

            foreach (var quest in trackedQuests)
            {
                if (quest?.Tasks == null) continue;

                int completedTasks = quest.Tasks.Count(t => t != null && t.IsFinished());
                int totalTasks = quest.Tasks.Count;

                // 检查是否有缓存的进度信息
                if (questProgressCache.TryGetValue(quest.ID, out var cachedProgress))
                {
                    // 如果进度发生变化
                    if (cachedProgress.completed != completedTasks || cachedProgress.total != totalTasks)
                    {
                        questProgressCache[quest.ID] = (completedTasks, totalTasks);
                        progressChanged = true;
                    }
                }
                else
                {
                    // 首次记录进度
                    questProgressCache[quest.ID] = (completedTasks, totalTasks);
                }
            }

            // 清理不再追踪的任务的进度缓存
            var trackedQuestIds = trackedQuests.Where(q => q != null).Select(q => q.ID).ToHashSet();
            var keysToRemove = questProgressCache.Keys.Where(id => !trackedQuestIds.Contains(id)).ToList();
            foreach (var key in keysToRemove)
            {
                questProgressCache.Remove(key);
            }

            // 如果有进度变化，更新UI
            if (progressChanged)
            {
                UpdateTrackedQuestsDisplay();
            }
            
            // 更新任务状态监听
            UpdateTaskStatusListeners();
        }
        
        private void UpdateTaskStatusListeners()
        {
            try
            {
                var trackedQuests = GetTrackedQuests();
                var currentTrackedQuestIds = trackedQuests.Where(q => q != null).Select(q => q.ID).ToHashSet();
                
                // 移除不再追踪的任务的监听
                var questsToRemove = listenedTasks.Keys.Where(id => !currentTrackedQuestIds.Contains(id)).ToList();
                foreach (var questId in questsToRemove)
                {
                    RemoveTaskListeners(questId);
                }
                
                // 为新追踪的任务添加监听
                foreach (var quest in trackedQuests)
                {
                    if (quest?.Tasks != null && !listenedTasks.ContainsKey(quest.ID))
                    {
                        AddTaskListeners(quest);
                    }
                }
            }
            catch
            {
            }
        }
        
        private void AddTaskListeners(Quest quest)
        {
            try
            {
                var taskList = new List<Task>();
                foreach (var task in quest.Tasks)
                {
                    if (task != null)
                    {
                        task.onStatusChanged += OnTaskStatusChanged;
                        taskList.Add(task);
                    }
                }
                listenedTasks[quest.ID] = taskList;
            }
            catch
            {
            }
        }
        
        private void RemoveTaskListeners(int questId)
        {
            try
            {
                if (listenedTasks.TryGetValue(questId, out var taskList))
                {
                    foreach (var task in taskList)
                    {
                        if (task != null)
                        {
                            task.onStatusChanged -= OnTaskStatusChanged;
                        }
                    }
                    listenedTasks.Remove(questId);
                }
            }
            catch
            {
            }
        }
        
        private void OnTaskStatusChanged(Task task)
        {
            try
            {
                // 任务状态变化时立即更新UI显示
                UpdateTrackedQuestsDisplay();
            }
            catch
            {
            }
        }

        private void CreateToggleButton(Canvas canvas)
        {
            try
            {
                // 创建独立的切换按钮，不依赖于面板
                toggleButton = new GameObject("TaskTrackerToggleButton");
                toggleButton.transform.SetParent(canvas.transform, false);

                // 设置按钮位置
                toggleButtonRect = toggleButton.AddComponent<RectTransform>();
                toggleButtonRect.sizeDelta = new Vector2(TOGGLE_BUTTON_WIDTH, TOGGLE_BUTTON_HEIGHT);
                
                // 注意：不在这里设置位置，让UpdatePanelAnchorsAndPivot和UpdatePanelPositions来处理
                // 这样可以确保初始化顺序正确

                // 添加按钮组件
                var button = toggleButton.AddComponent<Button>();
                var buttonImage = toggleButton.AddComponent<Image>();
                buttonImage.color = new Color(0, 0, 0, 0.7f); // 与面板一致的半透明黑色
                buttonImage.type = Image.Type.Sliced;

                // 添加按钮文本
                var textObj = new GameObject("ButtonText");
                textObj.transform.SetParent(toggleButton.transform, false);

                var textComponent = textObj.AddComponent<TextMeshProUGUI>();
                textComponent.text = "任\n务\n\nU"; // 竖向排列
                textComponent.fontSize = 14;
                textComponent.color = Color.white;
                textComponent.alignment = TextAlignmentOptions.Center;
                textComponent.fontStyle = FontStyles.Bold;
                textComponent.lineSpacing = -20; // 减少行间距

                // 设置文本布局
                var textRect = textComponent.rectTransform;
                textRect.anchorMin = Vector2.zero;
                textRect.anchorMax = Vector2.one;
                textRect.offsetMin = new Vector2(2, 2);
                textRect.offsetMax = new Vector2(-2, -2);

                // 设置按钮颜色状态
                var colors = button.colors;
                colors.normalColor = new Color(0, 0, 0, 0.7f);
                colors.highlightedColor = new Color(0, 0, 0, 0.9f);
                colors.pressedColor = new Color(0, 0, 0, 0.5f);
                colors.selectedColor = colors.highlightedColor;
                colors.disabledColor = new Color(0, 0, 0, 0.3f);
                button.colors = colors;

                // 绑定按钮事件
                button.onClick.AddListener(TogglePanel);

            }
            catch
            {
            }
        }

        private void CreatePanelContent()
        {
            if (mainPanel == null) return;

            try
            {
                // 创建内容容器
                var contentContainer = new GameObject("PanelContent");
                contentContainer.transform.SetParent(mainPanel.transform, false);

                var contentRect = contentContainer.AddComponent<RectTransform>();
                contentRect.anchorMin = Vector2.zero;
                contentRect.anchorMax = Vector2.one;
                contentRect.offsetMin = new Vector2(10, 10);
                contentRect.offsetMax = new Vector2(-10, -15); // 为切换按钮留出空间

                // 添加标题
                var titleObj = new GameObject("Title");
                titleObj.transform.SetParent(contentContainer.transform, false);

                var titleRect = titleObj.AddComponent<RectTransform>();
                titleRect.anchorMin = new Vector2(0, 1);
                titleRect.anchorMax = new Vector2(1, 1);
                titleRect.pivot = new Vector2(0.5f, 1);
                titleRect.sizeDelta = new Vector2(0, 40);
                titleRect.anchoredPosition = new Vector2(0, 0);

                var titleText = titleObj.AddComponent<TextMeshProUGUI>();
                titleText.text = "任务追踪器";
                titleText.fontSize = 32;
                titleText.color = Color.white;
                titleText.alignment = TextAlignmentOptions.Center;
                titleText.fontStyle = FontStyles.Bold;

                // 添加追踪任务列表显示区域
                CreateTrackedQuestsList(contentContainer);

            }
            catch
            {
            }
        }

        // 任务显示相关组件
        private GameObject? trackedQuestsContainer;
        private TextMeshProUGUI? noQuestsPlaceholder;

        private void CreateTrackedQuestsList(GameObject parent)
        {
            // 创建滚动区域显示追踪的任务
            var scrollArea = new GameObject("TrackedQuestsList");
            scrollArea.transform.SetParent(parent.transform, false);

            var scrollRect = scrollArea.AddComponent<RectTransform>();
            scrollRect.anchorMin = new Vector2(0, 0);
            scrollRect.anchorMax = new Vector2(1, 1);
            scrollRect.offsetMin = new Vector2(10, 10);
            scrollRect.offsetMax = new Vector2(-10, -50); // 为标题留出空间

            // 创建滚动视图组件
            var scrollView = scrollArea.AddComponent<ScrollRect>();
            scrollView.horizontal = false;
            scrollView.vertical = true;
            scrollView.scrollSensitivity = 20f;

            // 创建内容容器
            var contentObj = new GameObject("Content");
            contentObj.transform.SetParent(scrollArea.transform, false);
            trackedQuestsContainer = contentObj;

            var contentRect = contentObj.AddComponent<RectTransform>();
            contentRect.anchorMin = new Vector2(0, 1);
            contentRect.anchorMax = new Vector2(1, 1);
            contentRect.pivot = new Vector2(0.5f, 1);
            contentRect.anchoredPosition = Vector2.zero;
            contentRect.sizeDelta = new Vector2(0, 0);

            // 添加内容大小调整组件
            var contentSizeFitter = contentObj.AddComponent<ContentSizeFitter>();
            contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;

            // 添加垂直布局组件
            var verticalLayout = contentObj.AddComponent<VerticalLayoutGroup>();
            verticalLayout.spacing = 135f; // 调整任务容器间隔以适应5个任务的布局
            verticalLayout.padding = new RectOffset(5, 5, 5, 5);
            verticalLayout.childControlHeight = false;
            verticalLayout.childControlWidth = true;
            verticalLayout.childForceExpandHeight = false;
            verticalLayout.childForceExpandWidth = true;

            // 设置滚动视图的content
            scrollView.content = contentRect;

            // 创建占位文本（当没有追踪任务时显示）
            var placeholderObj = new GameObject("NoQuestsPlaceholder");
            placeholderObj.transform.SetParent(scrollArea.transform, false);

            var placeholderRect = placeholderObj.AddComponent<RectTransform>();
            placeholderRect.anchorMin = new Vector2(0, 0);
            placeholderRect.anchorMax = new Vector2(1, 1);
            placeholderRect.offsetMin = Vector2.zero;
            placeholderRect.offsetMax = Vector2.zero;

            noQuestsPlaceholder = placeholderObj.AddComponent<TextMeshProUGUI>();
            noQuestsPlaceholder.text = "当前没有追踪的任务\n\n使用任务详情页面的\"追踪\"按钮\n来添加任务到此列表\nU键可以收起本面板，L键可以切换靠左/右";
            noQuestsPlaceholder.fontSize = 18;
            noQuestsPlaceholder.color = new Color(0.8f, 0.8f, 0.8f, 1f);
            noQuestsPlaceholder.alignment = TextAlignmentOptions.Center;
            noQuestsPlaceholder.enableWordWrapping = true;

            // 初始显示占位文本
            UpdateTrackedQuestsDisplay();
        }

        private void UpdateTrackedQuestsDisplay()
        {
            if (trackedQuestsContainer == null || noQuestsPlaceholder == null) return;

            // 清除现有的任务显示
            foreach (Transform child in trackedQuestsContainer.transform)
            {
                Destroy(child.gameObject);
            }

            // 获取被追踪的任务
            var trackedQuests = GetTrackedQuests();

            if (trackedQuests.Count == 0)
            {
                // 显示占位文本
                noQuestsPlaceholder.gameObject.SetActive(true);
                trackedQuestsContainer.SetActive(false);
            }
            else
            {
                // 隐藏占位文本，显示任务列表
                noQuestsPlaceholder.gameObject.SetActive(false);
                trackedQuestsContainer.SetActive(true);

                // 为每个追踪的任务创建显示组件
                foreach (var quest in trackedQuests)
                {
                    CreateQuestDisplayItem(quest);
                }
            }
        }

        private List<Quest> GetTrackedQuests()
        {
            var trackedQuests = new List<Quest>();
            
            try
            {
                var questManager = QuestManager.Instance;
                if (questManager == null) return trackedQuests;

                var activeQuests = questManager.ActiveQuests;
                if (activeQuests == null) return trackedQuests;

                // 按追踪顺序获取任务
                foreach (int questId in trackedQuestIds)
                {
                    var quest = activeQuests.FirstOrDefault(q => q != null && q.ID == questId);
                    if (quest != null)
                    {
                        trackedQuests.Add(quest);
                    }
                }
            }
            catch
            {
            }

            return trackedQuests;
        }

        private void CreateQuestDisplayItem(Quest quest)
        {
            if (trackedQuestsContainer == null || quest == null) return;

            try
            {
                // 创建任务容器
                var questItem = new GameObject($"Quest_{quest.ID}");
                questItem.transform.SetParent(trackedQuestsContainer.transform, false);

                var questRect = questItem.AddComponent<RectTransform>();
                questRect.anchorMin = new Vector2(0, 1);
                questRect.anchorMax = new Vector2(1, 1);
                questRect.pivot = new Vector2(0.5f, 1);

                // 添加背景
                var background = questItem.AddComponent<Image>();
                background.color = new Color(0.15f, 0.15f, 0.15f, 0.9f); // 稍微提亮并增加透明度
                background.raycastTarget = false;

                // 添加垂直布局 - 减少间距
                var verticalLayout = questItem.AddComponent<VerticalLayoutGroup>();
                verticalLayout.spacing = 0.2f; // 从8f减少到3f
                verticalLayout.padding = new RectOffset(1, 1, 1, 1); // 进一步减少内边距，让内容更紧凑
                verticalLayout.childControlHeight = false;
                verticalLayout.childControlWidth = true;
                verticalLayout.childForceExpandHeight = false;
                verticalLayout.childForceExpandWidth = true;

                // 添加内容大小调整
                var contentSizeFitter = questItem.AddComponent<ContentSizeFitter>();
                contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;

                // 添加布局元素控制容器高度
                var questLayoutElement = questItem.AddComponent<LayoutElement>();
                questLayoutElement.preferredHeight = 220; // 设置任务容器的高度

                // 创建任务标题
                CreateQuestTitle(questItem, quest);

                // 创建子任务列表
                CreateTasksList(questItem, quest);

            }
            catch
            {
            }
        }

        private void CreateQuestTitle(GameObject parent, Quest quest)
        {
            var titleObj = new GameObject("QuestTitle");
            titleObj.transform.SetParent(parent.transform, false);

            var titleText = titleObj.AddComponent<TextMeshProUGUI>();
            titleText.text = " " + quest.DisplayName;
            titleText.fontSize = 28; // 从20增加到24
            titleText.fontStyle = FontStyles.Bold;
            titleText.color = quest.Complete ? new Color(0.4f, 0.8f, 0.4f) : Color.white;
            titleText.enableWordWrapping = true;

            var titleRect = titleObj.GetComponent<RectTransform>();
            titleRect.anchorMin = new Vector2(0, 1);
            titleRect.anchorMax = new Vector2(1, 1);
            titleRect.pivot = new Vector2(0.5f, 1);
            // titleRect.sizeDelta = new Vector2(0, 10);
            // titleRect.anchoredPosition = new Vector2(0, 0);

            var layoutElement = titleObj.AddComponent<LayoutElement>();
            layoutElement.preferredHeight = 1; // 减少高度，让标题更紧凑
        }

        private void CreateTasksList(GameObject parent, Quest quest)
        {
            if (quest.Tasks == null || quest.Tasks.Count == 0) return;

            // 创建单个任务列表容器
            var tasksObj = new GameObject("TasksList");
            tasksObj.transform.SetParent(parent.transform, false);

            var tasksRect = tasksObj.AddComponent<RectTransform>();
            tasksRect.anchorMin = new Vector2(0, 1);
            tasksRect.anchorMax = new Vector2(1, 1);
            tasksRect.pivot = new Vector2(0.5f, 1);

            // 构建所有任务的合并文本
            var allTasksText = BuildCombinedTasksText(quest.Tasks);

            // 创建单个文本组件显示所有任务
            var tasksTextComponent = tasksObj.AddComponent<TextMeshProUGUI>();
            tasksTextComponent.text = allTasksText;
            tasksTextComponent.fontSize = 18;
            tasksTextComponent.color = new Color(0.9f, 0.9f, 0.9f);
            tasksTextComponent.enableWordWrapping = true;
            tasksTextComponent.lineSpacing = -10; // 紧凑的行间距

            // 添加布局元素
            var layoutElement = tasksObj.AddComponent<LayoutElement>();
            layoutElement.flexibleWidth = 1;
            layoutElement.flexibleHeight = 1;
        }

        private string GetQuestIssuerInfo(Quest quest)
        {
            try
            {
                if (quest == null) return "";
                
                // 获取QuestGiverID
                var questGiverID = quest.QuestGiverID;
                
                // 尝试使用反射调用ToPlainText扩展方法进行本地化
                try
                {
                    string localizationKey = $"Character_{questGiverID}";
                    
                    // 查找ToPlainText扩展方法
                    var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
                    foreach (var assembly in assemblies)
                    {
                        var types = assembly.GetTypes();
                        foreach (var type in types)
                        {
                            if (type.IsSealed && type.IsAbstract) // 静态类
                            {
                                var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public)
                                    .Where(m => m.Name == "ToPlainText" && 
                                               m.GetParameters().Length == 1 && 
                                               m.GetParameters()[0].ParameterType == typeof(string));
                                
                                foreach (var method in methods)
                                {
                                    var localizedName = method.Invoke(null, new object[] { localizationKey }) as string;
                                    if (!string.IsNullOrEmpty(localizedName) && localizedName != localizationKey)
                                    {
                                        return localizedName;
                                    }
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
                
                // 如果本地化失败，尝试通过GameplayDataSettings获取发布人显示名称
                var gameplayDataSettings = typeof(UnityEngine.Object).Assembly.GetType("Duckov.Utilities.GameplayDataSettings");
                if (gameplayDataSettings != null)
                {
                    var questsProperty = gameplayDataSettings.GetProperty("Quests", BindingFlags.Public | BindingFlags.Static);
                    if (questsProperty != null)
                    {
                        var questsData = questsProperty.GetValue(null);
                        if (questsData != null)
                        {
                            var getDisplayNameMethod = questsData.GetType().GetMethod("GetDisplayName");
                            if (getDisplayNameMethod != null)
                            {
                                var displayName = getDisplayNameMethod.Invoke(questsData, new object[] { questGiverID }) as string;
                                if (!string.IsNullOrEmpty(displayName))
                                {
                                    return displayName;
                                }
                            }
                        }
                    }
                }
                
                // 如果无法获取显示名称，返回QuestGiverID的字符串表示
                return questGiverID.ToString();
            }
            catch
            {
                return "未知";
            }
        }

        private string GetTaskLocationInfo(Task task)
        {
            try
            {
                // 尝试获取不同类型任务的地点信息
                var taskType = task.GetType();
                
                // QuestTask_ReachLocation 类型
                if (taskType.Name == "QuestTask_ReachLocation")
                {
                    var locationProperty = taskType.GetProperty("TargetLocationDisplayName");
                    if (locationProperty != null)
                    {
                        var locationName = locationProperty.GetValue(task) as string;
                        if (!string.IsNullOrEmpty(locationName))
                        {
                            return locationName;
                        }
                    }
                }
                
                // QuestTask_KillCount 类型
                if (taskType.Name == "QuestTask_KillCount")
                {
                    var sceneProperty = taskType.GetProperty("requireSceneName");
                    if (sceneProperty != null)
                    {
                        var sceneName = sceneProperty.GetValue(task) as string;
                        if (!string.IsNullOrEmpty(sceneName) && sceneName != "Task_Desc_AnyScene")
                        {
                            return sceneName;
                        }
                    }
                }
                
                // QuestTask_Evacuate 类型
                if (taskType.Name == "QuestTask_Evacuate")
                {
                    var targetProperty = taskType.GetProperty("TargetDisplayName", 
                        System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    if (targetProperty != null)
                    {
                        var targetName = targetProperty.GetValue(task) as string;
                        if (!string.IsNullOrEmpty(targetName))
                        {
                            return targetName;
                        }
                    }
                }
                
                // 尝试从任务的Master（Quest）获取场景信息
                if (task.Master != null && task.Master.RequireSceneInfo != null)
                {
                    return task.Master.RequireSceneInfo.DisplayName;
                }
                
                // 如果都没有找到，返回空字符串
                return "";
            }
            catch
            {
                return "";
            }
        }

        private string BuildCombinedTasksText(List<Task> tasks)
        {
            var textBuilder = new System.Text.StringBuilder();
            
            if (tasks.Count > 0 && tasks[0] != null)
            {
                // 获取任务发布人信息
                string issuerInfo = "";
                if (tasks[0].Master != null)
                {
                    issuerInfo = GetQuestIssuerInfo(tasks[0].Master);
                }
                
                // 获取任务地点信息
                string locationInfo = GetTaskLocationInfo(tasks[0]);
                
                // 显示发布人和地点信息
                if (!string.IsNullOrEmpty(issuerInfo) || !string.IsNullOrEmpty(locationInfo))
                {
                    var infoText = "";
                    if (!string.IsNullOrEmpty(issuerInfo))
                    {
                        infoText += $"发布人：{issuerInfo}";
                    }
                    if (!string.IsNullOrEmpty(locationInfo))
                    {
                        if (!string.IsNullOrEmpty(infoText)) infoText += " ";
                        infoText += $"任务地点：{locationInfo}";
                    }
                    textBuilder.Append($"<color=#CCCCCC>{infoText}</color>\n");
                }
            }
            for (int i = 0; i < tasks.Count; i++)
            {
                var task = tasks[i];
                if (task == null) continue;

                // 根据任务完成状态设置颜色
                string taskColor = task.IsFinished() ? "#66CC66" : "#E6E6E6";
                string extraColor = task.IsFinished() ? "#4D9966" : "#CCCCCC";

                // 添加主任务描述，使用颜色标记
                textBuilder.Append($"<color={taskColor}>• {task.Description}</color>");
                
                // 如果任务已完成，添加完成标记
                if (task.IsFinished())
                {
                    textBuilder.Append(" <color=#66CC66>✓</color>");
                }

                

                // 添加额外描述信息
                if (task.ExtraDescriptsions != null && task.ExtraDescriptsions.Length > 0)
                {
                    foreach (var extraDesc in task.ExtraDescriptsions)
                    {
                        if (!string.IsNullOrEmpty(extraDesc))
                        {
                            textBuilder.Append($"\n<color={extraColor}>  {extraDesc}</color>");
                        }
                    }
                }

                // 如果不是最后一个任务，添加换行分隔
                if (i < tasks.Count - 1)
                {
                    textBuilder.Append("\n");
                }
            }

            return textBuilder.ToString();
        }



        private void CheckToggleInput()
        {
            // 检查是否在背包界面，如果是则不响应U键
            if (IsInventoryViewActive())
            {
                return;
            }
            
            // 检查U键输入 - 单击切换面板，双击打开原生任务界面和追踪面板
            if (Input.GetKeyDown(KeyCode.U) && !isAnimating)
            {
                float currentTime = Time.unscaledTime;
                
                // 检查是否为双击
                if (isWaitingForDoubleClick && currentTime - lastUKeyPressTime <= DOUBLE_CLICK_TIME)
                {
                    // 双击：取消单击协程，执行双击逻辑
                    if (singleClickCoroutine != null)
                    {
                        StopCoroutine(singleClickCoroutine);
                        singleClickCoroutine = null;
                    }
                    isWaitingForDoubleClick = false;
                    OpenQuestViewAndTracker();
                }
                else
                {
                    // 第一次点击：启动延迟判断
                    lastUKeyPressTime = currentTime;
                    isWaitingForDoubleClick = true;
                    
                    // 启动单击延迟协程
                    if (singleClickCoroutine != null)
                    {
                        StopCoroutine(singleClickCoroutine);
                    }
                    singleClickCoroutine = StartCoroutine(HandleSingleClick());
                }
            }
            
            // 检查ESC键输入 - 仅收起面板（直接隐藏，不播放动画）
            if (Input.GetKeyDown(KeyCode.Escape) && isPanelVisible)
            {
                HidePanel(); // 直接隐藏面板，避免因游戏暂停导致动画停止
            }

            // 检测Tab键输入 - 仅收起面板
            if (Input.GetKeyDown(KeyCode.Tab) && !isAnimating && isPanelVisible)
            {
                TogglePanel(); // 只有在面板展开时才响应Tab键
            }
        }

        private void CheckPanelPositionToggleInput()
        {
            // 检查是否在背包界面，如果是则不响应L键
            if (IsInventoryViewActive())
            {
                return;
            }
            
            // 检查L键输入 - 切换面板位置（左侧/右侧）
            if (Input.GetKeyDown(KeyCode.L) && !isAnimating && panelRect != null)
            {
                TogglePanelPosition();
            }
        }

        private void TogglePanelPosition()
        {
            if (isAnimating) return;
            
            // 切换面板位置状态
            isPanelOnLeft = !isPanelOnLeft;
            
            // 直接切换位置，不使用动画
            UpdatePanelAnchorsAndPivot();
            UpdatePanelPositions(isPanelVisible);
            
            // 延时重建UI以修复布局问题
            StartCoroutine(DelayedUIRebuild());
        }

        private bool IsInventoryViewActive()
        {
            // 检查当前活跃的View是否为背包相关界面
            var activeView = View.ActiveView;
            if (activeView == null) return false;
            
            // 检查是否为InventoryView或LootView
            return activeView is InventoryView || activeView is LootView;
        }

        private IEnumerator DelayedUIRebuild()
        {
            // 等待一帧，让位置切换完全完成
            yield return null;
            
            // 再等待一小段时间确保布局稳定
            yield return new WaitForSecondsRealtime(0.1f);
            
            // 重建任务显示以修复布局问题
            UpdateTrackedQuestsDisplay();
            
            // 强制重新计算布局
            if (panelRect != null)
            {
                UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(panelRect);
            }
        }

        private void TogglePanel()
        {
            if (isAnimating || panelRect == null) return;

            StartCoroutine(AnimatePanel());
        }

        private IEnumerator HandleSingleClick()
        {
            // 等待双击时间窗口
            yield return new WaitForSecondsRealtime(DOUBLE_CLICK_TIME);
            
            // 如果没有被双击打断，执行单击逻辑
            if (isWaitingForDoubleClick)
            {
                isWaitingForDoubleClick = false;
                singleClickCoroutine = null;
                TogglePanel();
            }
        }

        private void OpenQuestViewAndTracker()
        {
            try
            {
                // 检查游戏状态限制
                var gameManagerType = System.Type.GetType("GameManager, TeamSoda.Duckov.Core");
                var dialogueUIType = System.Type.GetType("DialogueUI, TeamSoda.Duckov.Core");
                
                bool canOperateQuestView = true;
                
                // 检查游戏是否暂停
                if (gameManagerType != null)
                {
                    var pausedProperty = gameManagerType.GetProperty("Paused", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                    if (pausedProperty != null && (bool)pausedProperty.GetValue(null))
                    {
                        canOperateQuestView = false;
                    }
                }
                
                // 检查对话界面是否活跃
                if (dialogueUIType != null && canOperateQuestView)
                {
                    var activeProperty = dialogueUIType.GetProperty("Active", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                    if (activeProperty != null && (bool)activeProperty.GetValue(null))
                    {
                        canOperateQuestView = false;
                    }
                }
                
                bool questViewWasOpened = false;
                
                if (canOperateQuestView)
                {
                    // 获取View基类和QuestView类型
                    var viewType = System.Type.GetType("Duckov.UI.View, TeamSoda.Duckov.Core");
                    var questViewType = System.Type.GetType("Duckov.Quests.UI.QuestView, TeamSoda.Duckov.Core");
                    
                    if (viewType != null && questViewType != null)
                    {
                        // 获取当前活跃的视图
                        var activeViewProperty = viewType.GetProperty("ActiveView", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                        if (activeViewProperty != null)
                        {
                            var activeView = activeViewProperty.GetValue(null);
                            
                            if (activeView == null)
                            {
                                // 没有活跃视图，打开任务界面
                                var showMethod = questViewType.GetMethod("Show", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                                if (showMethod != null)
                                {
                                    showMethod.Invoke(null, null);
                                    questViewWasOpened = true;
                                }
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                }

                // 只有在打开任务界面时才自动显示追踪面板
                if (questViewWasOpened && !isPanelVisible)
                {
                    TogglePanel();
                }
            }
            catch
            {
                // 如果操作原生界面失败，至少确保追踪面板可用
                if (!isPanelVisible)
                {
                    TogglePanel();
                }
            }
        }

        private void HidePanel()
        {
            if (panelRect == null || !isPanelVisible) return;

            // 直接设置面板和按钮位置，不播放动画
            isPanelVisible = false;
            UpdatePanelPositions(false);
            
        }

        private IEnumerator AnimatePanel()
        {
            if (panelRect == null || toggleButtonRect == null)
            {
                isAnimating = false;
                yield break;
            }

            isAnimating = true;
            isPanelVisible = !isPanelVisible;

            float panelStartX = panelRect.anchoredPosition.x;
            float buttonStartX = toggleButtonRect.anchoredPosition.x;
            
            float panelTargetX, buttonTargetX;
            
            if (isPanelVisible)
            {
                // 展开面板
                panelTargetX = 0f;
                buttonTargetX = isPanelOnLeft ? PANEL_WIDTH : -PANEL_WIDTH;
            }
            else
            {
                // 收起面板
                panelTargetX = isPanelOnLeft ? -PANEL_WIDTH : PANEL_WIDTH;
                buttonTargetX = 0f;
            }
            
            float elapsedTime = 0f;

            while (elapsedTime < ANIMATION_DURATION)
            {
                elapsedTime += Time.deltaTime;
                float t = elapsedTime / ANIMATION_DURATION;
                
                // 使用平滑的缓动函数
                t = 1f - Mathf.Pow(1f - t, 3f); // OutCubic easing
                
                float currentPanelX = Mathf.Lerp(panelStartX, panelTargetX, t);
                float currentButtonX = Mathf.Lerp(buttonStartX, buttonTargetX, t);
                
                panelRect.anchoredPosition = new Vector2(currentPanelX, panelRect.anchoredPosition.y);
                toggleButtonRect.anchoredPosition = new Vector2(currentButtonX, toggleButtonRect.anchoredPosition.y);
                
                yield return null;
            }

            // 确保最终位置准确
            panelRect.anchoredPosition = new Vector2(panelTargetX, panelRect.anchoredPosition.y);
            toggleButtonRect.anchoredPosition = new Vector2(buttonTargetX, toggleButtonRect.anchoredPosition.y);
            isAnimating = false;
            
            // 保存面板状态
            SaveData();
            

        }

        private void UpdatePanelPositions(bool isVisible)
        {
            if (panelRect == null || toggleButtonRect == null) return;

            // 计算按钮的垂直偏移
            float verticalOffset = (GetPanelHeight() / 2) - (TOGGLE_BUTTON_HEIGHT / 2);
            
            if (isPanelOnLeft)
            {
                // 左侧位置
                if (isVisible)
                {
                    panelRect.anchoredPosition = new Vector2(0f, 0);
                    toggleButtonRect.anchoredPosition = new Vector2(PANEL_WIDTH, verticalOffset);
                }
                else
                {
                    panelRect.anchoredPosition = new Vector2(-PANEL_WIDTH, 0);
                    toggleButtonRect.anchoredPosition = new Vector2(0f, verticalOffset);
                }
            }
            else
            {
                // 右侧位置
                if (isVisible)
                {
                    panelRect.anchoredPosition = new Vector2(0f, 0);
                    toggleButtonRect.anchoredPosition = new Vector2(-PANEL_WIDTH, verticalOffset);
                }
                else
                {
                    panelRect.anchoredPosition = new Vector2(PANEL_WIDTH, 0);
                    toggleButtonRect.anchoredPosition = new Vector2(0f, verticalOffset);
                }
            }
        }

        private IEnumerator AnimatePanelPositionChange(bool wasVisible)
        {
            isAnimating = true;
            
            // 第一阶段：如果面板是展开的，先收起
            if (wasVisible)
            {
                yield return StartCoroutine(AnimatePanelToHidden());
            }
            
            // 第二阶段：更新锚点和位置到新的一侧
            UpdatePanelAnchorsAndPivot();
            UpdatePanelPositions(false); // 设置为收起状态的位置
            
            // 第三阶段：如果原来是展开的，重新展开
            if (wasVisible)
            {
                yield return StartCoroutine(AnimatePanelToVisible());
            }
            
            isAnimating = false;
        }

        private void UpdatePanelAnchorsAndPivot()
        {
            if (panelRect == null || toggleButtonRect == null) return;
            
            if (isPanelOnLeft)
            {
                // 左侧锚点设置
                panelRect.anchorMin = new Vector2(0, 0.5f);
                panelRect.anchorMax = new Vector2(0, 0.5f);
                panelRect.pivot = new Vector2(0, 0.5f);
                
                toggleButtonRect.anchorMin = new Vector2(0, 0.5f);
                toggleButtonRect.anchorMax = new Vector2(0, 0.5f);
                toggleButtonRect.pivot = new Vector2(0, 0.5f);
            }
            else
            {
                // 右侧锚点设置
                panelRect.anchorMin = new Vector2(1, 0.5f);
                panelRect.anchorMax = new Vector2(1, 0.5f);
                panelRect.pivot = new Vector2(1, 0.5f);
                
                toggleButtonRect.anchorMin = new Vector2(1, 0.5f);
                toggleButtonRect.anchorMax = new Vector2(1, 0.5f);
                toggleButtonRect.pivot = new Vector2(1, 0.5f);
            }
        }

        private IEnumerator AnimatePanelToHidden()
        {
            if (panelRect == null || toggleButtonRect == null)
            {
                yield break;
            }

            float startX = panelRect.anchoredPosition.x;
            float buttonStartX = toggleButtonRect.anchoredPosition.x;
            float verticalOffset = (GetPanelHeight() / 2) - (TOGGLE_BUTTON_HEIGHT / 2);
            
            float targetX, buttonTargetX;
            
            if (isPanelOnLeft)
            {
                targetX = -PANEL_WIDTH;
                buttonTargetX = 0f;
            }
            else
            {
                targetX = PANEL_WIDTH;
                buttonTargetX = 0f;
            }
            
            float elapsedTime = 0f;
            while (elapsedTime < ANIMATION_DURATION)
            {
                elapsedTime += Time.deltaTime;
                float t = elapsedTime / ANIMATION_DURATION;
                t = 1f - Mathf.Pow(1f - t, 3f); // OutCubic easing
                
                float currentX = Mathf.Lerp(startX, targetX, t);
                float currentButtonX = Mathf.Lerp(buttonStartX, buttonTargetX, t);
                
                panelRect.anchoredPosition = new Vector2(currentX, 0);
                toggleButtonRect.anchoredPosition = new Vector2(currentButtonX, verticalOffset);
                
                yield return null;
            }
            
            panelRect.anchoredPosition = new Vector2(targetX, 0);
            toggleButtonRect.anchoredPosition = new Vector2(buttonTargetX, verticalOffset);
            isPanelVisible = false;
        }

        private IEnumerator AnimatePanelToVisible()
        {
            if (panelRect == null || toggleButtonRect == null)
            {
                yield break;
            }

            float startX = panelRect.anchoredPosition.x;
            float buttonStartX = toggleButtonRect.anchoredPosition.x;
            float verticalOffset = (GetPanelHeight() / 2) - (TOGGLE_BUTTON_HEIGHT / 2);
            
            float targetX = 0f;
            float buttonTargetX;
            
            if (isPanelOnLeft)
            {
                buttonTargetX = PANEL_WIDTH;
            }
            else
            {
                buttonTargetX = -PANEL_WIDTH;
            }
            
            float elapsedTime = 0f;
            while (elapsedTime < ANIMATION_DURATION)
            {
                elapsedTime += Time.deltaTime;
                float t = elapsedTime / ANIMATION_DURATION;
                t = 1f - Mathf.Pow(1f - t, 3f); // OutCubic easing
                
                float currentX = Mathf.Lerp(startX, targetX, t);
                float currentButtonX = Mathf.Lerp(buttonStartX, buttonTargetX, t);
                
                panelRect.anchoredPosition = new Vector2(currentX, 0);
                toggleButtonRect.anchoredPosition = new Vector2(currentButtonX, verticalOffset);
                
                yield return null;
            }
            
            panelRect.anchoredPosition = new Vector2(targetX, 0);
            toggleButtonRect.anchoredPosition = new Vector2(buttonTargetX, verticalOffset);
            isPanelVisible = true;
        }

        private void CleanupMainPanel()
        {
            if (mainPanel != null)
            {
                Destroy(mainPanel);
                mainPanel = null;
                panelRect = null;
            }
            
            // 独立清理切换按钮
            if (toggleButton != null)
            {
                Destroy(toggleButton);
                toggleButton = null;
                toggleButtonRect = null;
            }
        }
        
        private void CleanupTaskListeners()
        {
            try
            {
                // 清理所有任务状态监听器
                foreach (var questId in listenedTasks.Keys.ToList())
                {
                    RemoveTaskListeners(questId);
                }
                listenedTasks.Clear();
            }
            catch
            {
            }
        }

        #endregion

        private void RegisterQuestEvents()
        {
            // 监听任务状态变化事件
            Quest.onQuestStatusChanged += OnQuestStatusChanged;
            // 监听任务列表变化事件
            QuestManager.onQuestListsChanged += OnQuestListsChanged;
            // 监听界面激活变化事件，确保任务界面打开时能正确排序
            View.OnActiveViewChanged += OnActiveViewChanged;
        }

        private void UnregisterQuestEvents()
        {
            // 取消监听任务状态变化事件
            Quest.onQuestStatusChanged -= OnQuestStatusChanged;
            QuestManager.onQuestListsChanged -= OnQuestListsChanged;
            View.OnActiveViewChanged -= OnActiveViewChanged;
        }

        private void OnQuestStatusChanged(Quest quest)
        {
            if (quest != null && quest.Complete && trackedQuestIds.Contains(quest.ID))
            {
                // 任务完成时自动取消追踪
                RemoveFromTrackedQuests(quest.ID);
                
                // 刷新任务列表显示
                RefreshQuestListOrder();
            }
            
            // 更新任务追踪器显示
            UpdateTrackedQuestsDisplay();
        }

        private void OnQuestListsChanged(QuestManager questManager)
        {
            // 当任务列表发生变化时，刷新排序
            RefreshQuestListOrder();
            
            // 更新任务追踪器显示
            UpdateTrackedQuestsDisplay();
        }

        private void OnActiveViewChanged()
        {
            // 当激活的界面发生变化时，检查是否是任务界面
            if (View.ActiveView is QuestView)
            {
                // 延迟一帧执行，确保界面完全初始化
                StartCoroutine(DelayedRefreshQuestListOrder());
            }
        }

        private IEnumerator DelayedRefreshQuestListOrder()
        {
            // 等待一帧，确保QuestView完全初始化
            yield return null;
            RefreshQuestListOrder();
        }

        private void CheckQuestDetailsChange()
        {
            var questView = QuestView.Instance;
            if (questView == null) return;

            var questDetails = questView.GetComponentInChildren<QuestViewDetails>();
            if (questDetails == null) return;

            var currentQuest = questDetails.Target;
            
            // 如果任务发生变化
            if (currentQuest != lastTrackedQuest)
            {
                CleanupTrackButton();
                lastTrackedQuest = currentQuest;
                
                if (currentQuest != null)
                {
                    currentQuestDetails = questDetails;
                    CreateTrackButton(questDetails);
                }
            }
        }

        private void CreateTrackButton(QuestViewDetails questDetails)
        {
            try
            {
                // 获取奖励容器
                var rewardsParent = GetRewardsParent(questDetails);
                if (rewardsParent == null)
                {
                    return;
                }

                // 创建追踪按钮容器
                var buttonContainer = new GameObject("TrackButtonContainer");
                buttonContainer.transform.SetParent(rewardsParent.parent, false);
                
                // 设置容器在奖励容器之后，并添加一些间距
                buttonContainer.transform.SetSiblingIndex(rewardsParent.GetSiblingIndex() + 1);

                // 添加垂直布局组件和内容大小适配器
                var verticalLayout = buttonContainer.AddComponent<VerticalLayoutGroup>();
                verticalLayout.childAlignment = TextAnchor.MiddleCenter;
                verticalLayout.padding = new RectOffset(0, 0, 20, 10); // 上边距20，下边距10
                verticalLayout.spacing = 10;

                var contentSizeFitter = buttonContainer.AddComponent<ContentSizeFitter>();
                contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;

                // 创建按钮
                trackButton = new GameObject("TrackButton");
                trackButton.transform.SetParent(buttonContainer.transform, false);

                // 添加按钮组件
                var button = trackButton.AddComponent<Button>();
                var image = trackButton.AddComponent<Image>();
                
                // 检查当前任务是否已被追踪
                bool isTracked = currentQuestDetails?.Target != null && 
                                trackedQuestIds.Contains(currentQuestDetails.Target.ID);
                
                // 设置按钮样式（移除圆角效果）
                image.color = isTracked ? new Color(0.6f, 0.2f, 0.2f, 0.9f) : new Color(0.15f, 0.25f, 0.4f, 0.9f);
                image.type = Image.Type.Sliced;
                
                // 添加按钮文本
                var textObj = new GameObject("Text");
                textObj.transform.SetParent(trackButton.transform, false);
                
                var textComponent = textObj.AddComponent<TextMeshProUGUI>();
                textComponent.text = isTracked ? "取消追踪" : "追踪";
                textComponent.fontSize = 24;
                textComponent.color = Color.white;
                textComponent.alignment = TextAlignmentOptions.Center;
                textComponent.fontStyle = FontStyles.Bold;

                // 设置文本布局
                var textRect = textComponent.rectTransform;
                textRect.anchorMin = Vector2.zero;
                textRect.anchorMax = Vector2.one;
                textRect.offsetMin = new Vector2(10, 5); // 左右内边距10，上下内边距5
                textRect.offsetMax = new Vector2(-10, -5);

                // 设置按钮大小和布局
                var buttonRect = trackButton.GetComponent<RectTransform>();
                buttonRect.sizeDelta = new Vector2(120, 35); // 稍微大一点的按钮
                
                // 添加布局元素以确保正确的大小
                var layoutElement = trackButton.AddComponent<LayoutElement>();
                layoutElement.preferredWidth = 120;
                layoutElement.preferredHeight = 35;

                // 设置按钮的颜色状态
                var colors = button.colors;
                if (isTracked)
                {
                    // 已追踪状态 - 红色系
                    colors.normalColor = new Color(0.6f, 0.2f, 0.2f, 0.9f);
                    colors.highlightedColor = new Color(0.8f, 0.3f, 0.3f, 1f);
                    colors.pressedColor = new Color(0.5f, 0.15f, 0.15f, 1f);
                }
                else
                {
                    // 未追踪状态 - 蓝色系
                    colors.normalColor = new Color(0.15f, 0.25f, 0.4f, 0.9f);
                    colors.highlightedColor = new Color(0.2f, 0.35f, 0.6f, 1f);
                    colors.pressedColor = new Color(0.1f, 0.2f, 0.35f, 1f);
                }
                colors.selectedColor = colors.highlightedColor;
                colors.disabledColor = new Color(0.5f, 0.5f, 0.5f, 0.5f);
                button.colors = colors;

                // 绑定按钮事件
                button.onClick.AddListener(OnTrackButtonClicked);
            }
            catch
            {
                // Error creating track button
            }
        }

        private Transform? GetRewardsParent(QuestViewDetails questDetails)
        {
            // 通过反射获取私有字段 rewardsParent
            var field = typeof(QuestViewDetails).GetField("rewardsParent", 
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            
            if (field != null)
            {
                return field.GetValue(questDetails) as Transform;
            }
            
            return null;
        }

        private void OnTrackButtonClicked()
        {
            if (currentQuestDetails?.Target == null) return;

            var quest = currentQuestDetails.Target;
            bool isCurrentlyTracked = trackedQuestIds.Contains(quest.ID);

            if (isCurrentlyTracked)
            {
                // 取消追踪
                RemoveFromTrackedQuests(quest.ID);
            }
            else
            {
                // 添加追踪
                AddToTrackedQuests(quest.ID);
            }

            // 直接刷新按钮显示（移除动画优化）
            CleanupTrackButton();
            CreateTrackButton(currentQuestDetails);
            
            // 刷新任务列表顺序
            RefreshQuestListOrder();
            
            // 更新任务追踪器显示
            UpdateTrackedQuestsDisplay();
        }

        private void AddToTrackedQuests(int questId)
        {
            if (trackedQuestIds.Contains(questId)) return;

            // 如果已达到最大追踪数量，拒绝新的追踪请求
            if (trackedQuestIds.Count >= MAX_TRACKED_QUESTS)
            {
                return; // 直接返回，不添加新任务
            }

            trackedQuestIds.Add(questId);
            
            // 更新面板高度
            UpdatePanelHeight();
            
            // 保存数据
            SaveData();
        }

        private void RemoveFromTrackedQuests(int questId)
        {
            trackedQuestIds.Remove(questId);
            
            // 更新面板高度
            UpdatePanelHeight();
            
            // 保存数据
            SaveData();
        }

        private void RefreshQuestListOrder()
        {
            try
            {
                var questView = QuestView.Instance;
                if (questView == null) return;

                // 获取任务条目父容器
                var questEntryParent = GetQuestEntryParent(questView);
                if (questEntryParent == null) return;

                // 获取所有任务条目
                var questEntries = questEntryParent.GetComponentsInChildren<QuestEntry>();
                if (questEntries == null || questEntries.Length == 0) return;

                // 按追踪状态排序：被追踪的任务置顶，按追踪顺序排列
                var sortedEntries = questEntries
                    .Where(entry => entry.Target != null)
                    .OrderBy(entry => 
                    {
                        int questId = entry.Target.ID;
                        int trackedIndex = trackedQuestIds.IndexOf(questId);
                        // 被追踪的任务返回其在追踪栈中的索引（越小越靠前）
                        // 未被追踪的任务返回一个大数值，保持原有顺序
                        return trackedIndex >= 0 ? trackedIndex : 1000 + questId;
                    })
                    .ToList();

                // 重新排列UI顺序
                for (int i = 0; i < sortedEntries.Count; i++)
                {
                    sortedEntries[i].transform.SetSiblingIndex(i);
                }

            }
            catch
            {
                // Error refreshing quest list order
            }
        }

        private void UpdateQuestStarIndicators()
        {
            try
            {
                var questView = QuestView.Instance;
                if (questView == null) return;

                var questEntryParent = GetQuestEntryParent(questView);
                if (questEntryParent == null) return;

                var questEntries = questEntryParent.GetComponentsInChildren<QuestEntry>();
                if (questEntries == null) return;

                // 获取当前所有任务ID
                var currentQuestIds = questEntries.Where(e => e.Target != null).Select(e => e.Target.ID).ToHashSet();
                
                // 清理所有现有的五角星，防止位置错位
                foreach (var starPair in questStarIndicators.ToList())
                {
                    if (starPair.Value != null)
                    {
                        Destroy(starPair.Value);
                    }
                }
                questStarIndicators.Clear();

                // 重新为被追踪的任务创建五角星
                foreach (var entry in questEntries)
                {
                    if (entry.Target == null) continue;

                    int questId = entry.Target.ID;
                    bool isTracked = trackedQuestIds.Contains(questId);

                    if (isTracked)
                    {
                        // 创建五角星标识
                        CreateStarIndicator(entry, questId);
                    }
                }
            }
            catch
            {
                // Error updating star indicators
            }
        }

        private void CreateStarIndicator(QuestEntry questEntry, int questId)
        {
            try
            {
                // 创建五角星容器
                var starContainer = new GameObject("StarIndicator");
                starContainer.transform.SetParent(questEntry.transform, false);

                // 设置五角星位置（左上角）- 使用更精确的定位
                var starRect = starContainer.AddComponent<RectTransform>();
                
                // 设置锚点到左上角
                starRect.anchorMin = new Vector2(0, 1);
                starRect.anchorMax = new Vector2(0, 1);
                starRect.pivot = new Vector2(0.5f, 0.5f); // 中心轴心点
                
                // 设置位置和大小
                starRect.sizeDelta = new Vector2(26, 26);
                starRect.anchoredPosition = new Vector2(12, -12); // 从左上角偏移12像素
                
                // 添加背景圆形（可选，用于更好的可见性）
                var bgImage = starContainer.AddComponent<Image>();
                bgImage.color = new Color(0, 0, 0, 0f); // 全透明黑色背景
                bgImage.type = Image.Type.Simple;

                // 创建简单的五角星形状（使用Unicode字符）
                var starTextObj = new GameObject("StarText");
                starTextObj.transform.SetParent(starContainer.transform, false);
                
                var starText = starTextObj.AddComponent<TextMeshProUGUI>();
                starText.text = "★";
                starText.fontSize = 18; // 稍微调小字体以适应容器
                starText.color = new Color(1f, 0.8f, 0f, 1f);
                starText.alignment = TextAlignmentOptions.Center;
                starText.fontStyle = FontStyles.Bold;

                // 设置文本布局 - 填满整个容器
                var textRect = starText.rectTransform;
                textRect.anchorMin = Vector2.zero;
                textRect.anchorMax = Vector2.one;
                textRect.offsetMin = Vector2.zero;
                textRect.offsetMax = Vector2.zero;

                // 确保五角星在最上层
                starContainer.transform.SetAsLastSibling();

                // 添加到字典中管理
                questStarIndicators[questId] = starContainer;
            }
            catch
            {
                // Error creating star indicator
            }
        }

        private void CleanupAllStarIndicators()
        {
            foreach (var star in questStarIndicators.Values)
            {
                if (star != null)
                {
                    Destroy(star);
                }
            }
            questStarIndicators.Clear();
        }

        private Transform? GetQuestEntryParent(QuestView questView)
        {
            // 通过反射获取私有字段 questEntryParent
            var field = typeof(QuestView).GetField("questEntryParent", 
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            
            if (field != null)
            {
                return field.GetValue(questView) as Transform;
            }
            
            return null;
        }

        private void CleanupTrackButton()
        {
            if (trackButton != null)
            {
                // 销毁按钮容器（包含按钮）
                var container = trackButton.transform.parent?.gameObject;
                if (container != null && container.name == "TrackButtonContainer")
                {
                    Destroy(container);
                }
                trackButton = null;
            }
        }

        // 存档相关方法
        private void OnLevelInitialized()
        {
            if (!isGameInitialized)
            {
                isGameInitialized = true;
                shouldHideOnStartup = false;
                
                // 显示面板和按钮
                if (mainPanel != null)
                {
                    mainPanel.SetActive(true);
                }
                if (toggleButton != null)
                {
                    toggleButton.SetActive(true);
                }
                
                // 加载存档数据
                LoadData();
            }
        }

        private void OnMainMenuAwake()
        {
            // 返回主菜单时重置面板状态为完全隐藏
            isPanelVisible = false;
            shouldHideOnStartup = true;
            isGameInitialized = false;
            
            // 隐藏面板和按钮
            if (mainPanel != null)
            {
                mainPanel.SetActive(false);
            }
            if (toggleButton != null)
            {
                toggleButton.SetActive(false);
            }
            
            // 保存状态
            SaveData();
        }

        private string GetCurrentSaveKey()
        {
            return SAVE_KEY_PREFIX + SavesSystem.CurrentSlot;
        }

        private void SaveData()
        {
            if (!isGameInitialized) return;
            
            try
            {
                string saveKey = GetCurrentSaveKey();
                
                // 保存追踪的任务ID列表
                string questIdsJson = string.Join(",", trackedQuestIds);
                PlayerPrefs.SetString(saveKey + "_QuestIds", questIdsJson);
                
                // 保存面板显示状态
                PlayerPrefs.SetInt(saveKey + "_PanelVisible", isPanelVisible ? 1 : 0);
                
                // 立即保存到磁盘
                PlayerPrefs.Save();
            }
            catch
            {
                // 静默处理存档错误
            }
        }

        private void LoadData()
        {
            if (!isGameInitialized) return;
            
            try
            {
                string saveKey = GetCurrentSaveKey();
                
                // 加载追踪的任务ID列表
                string questIdsJson = PlayerPrefs.GetString(saveKey + "_QuestIds", "");
                List<int> savedQuestIds = new List<int>();
                
                if (!string.IsNullOrEmpty(questIdsJson))
                {
                    string[] questIdStrings = questIdsJson.Split(',');
                    foreach (string questIdStr in questIdStrings)
                    {
                        if (int.TryParse(questIdStr.Trim(), out int questId))
                        {
                            savedQuestIds.Add(questId);
                        }
                    }
                }
                
                // 校验并加载追踪列表
                ValidateAndLoadTrackedQuests(savedQuestIds);
                
                // 恢复面板显示状态
                bool savedPanelVisible = PlayerPrefs.GetInt(saveKey + "_PanelVisible", 1) == 1;
                if (savedPanelVisible != isPanelVisible)
                {
                    TogglePanel();
                }
            }
            catch
            {
                // 静默处理加载错误，使用默认状态
            }
        }

        private void ValidateAndLoadTrackedQuests(List<int> savedQuestIds)
        {
            if (savedQuestIds == null) return;
            
            // 清空当前追踪列表
            trackedQuestIds.Clear();
            
            // 获取当前活跃任务列表
            var questManager = QuestManager.Instance;
            if (questManager == null) return;
            
            var activeQuests = questManager.ActiveQuests;
            var activeQuestIds = new HashSet<int>(activeQuests.Select(q => q.ID));
            
            // 只添加仍然活跃的任务
            foreach (int questId in savedQuestIds)
            {
                if (activeQuestIds.Contains(questId) && trackedQuestIds.Count < MAX_TRACKED_QUESTS)
                {
                    trackedQuestIds.Add(questId);
                }
            }
            
            // 更新面板高度
            UpdatePanelHeight();
            
            // 刷新面板内容
            UpdateTrackedQuestsDisplay();
            
            // 初始化任务状态监听
            UpdateTaskStatusListeners();
        }
    }
}